<?php

namespace app\admin\controller\weixin\template;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use think\Cache;
use addons\weixin\library\WechatTemplateService;

/**
 * 微信模板
 *
 * @icon fa fa-circle-o
 */
class Wechat extends Backend
{
    
    /**
     * Wechat模型对象
     * @var \app\admin\model\weixin\template\Wechat
     */
    protected $model = null;
    protected $cacheTag = '_system_wechat';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\weixin\template\Wechat;

        //得到所属行业
        $industry = Cache::tag($this->cacheTag)->remember('_wechat_industry', function () {
            try {
                $cache = WechatTemplateService::getIndustry();
                if (!$cache) {
                    return [];
                }
                Cache::tag($this->cacheTag, ['_wechat_industry']);
                return $cache;
            } catch (\Exception $e) {
                return $e->getMessage();
            }
        }, 0) ?: [];
        !is_array($industry) && $industry = [];
        $this->assign('industry', $industry);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = method_exists($this, 'preExcludeFields') ? $this->preExcludeFields($params) : $params;

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = method_exists($this, 'preExcludeFields') ? $this->preExcludeFields($params) : $params;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    public function send_school($ids = ""){
        $data=DB::name('admin')
            ->alias('a')
            ->field('b.id as b_id,a.s_id,b.school,b.openid,b.name')
            ->join('school_bind b','a.s_id=b.school_id','left')
            ->where("b.status='1' and b.is_del=0  and a.is_receipt=0")
            ->select();

        $wx=new WechatTemplateService();
        $thismonth = date('m');
        $thisyear = date('Y');
        $startDay = $thisyear . '-' . $thismonth . '-1';
        $endDay = $thisyear . '-' . $thismonth . '-' . date('t', strtotime($startDay));

        $start_time= strtotime($startDay);//当前月的月初时间戳
        $end_time = strtotime($endDay)+86400;//当前月的月末时间戳
        $a=0;
        $arr=[];
        foreach ($data as $k=>$v){
            $views=DB::name('zd_user_school_click')->where("create_time>".$start_time." and create_time<".$end_time."")->where(['school_id'=>$v['s_id']])->group('user_id')->count();
            $follows=DB::name('zd_user_school_follow')->where("create_time>".$start_time." and create_time<".$end_time."  and type=0")->where(['school_id'=>$v['s_id']])->count();
            $content=array('first' => '您好，已为您生成本月运营报告，请查收',
                'keyword1' => '运营月报',
                'keyword2' => date('Y-m-d H:i:s', time()),
                'remark' => "".$v['school']."本月访客 ".$views." 人，新增关注用户 ".$follows." 人 更多信息请登录后台查看");
            if ($v['openid']){
                $res=$wx->sendTemplate1($v['openid'],2,$content);
                $arr[$a]['school_id']=$v['s_id'];
                $arr[$a]['school']=$v['school'];
                $arr[$a]['openid']=$v['openid'];
                $arr[$a]['name']=$v['name'];
                $arr[$a]['code']=$res['errcode']?$res['errcode']:1;
                $arr[$a]['msg']=$res['errmsg']?$res['errmsg']:'fail';
                $arr[$a]['time']=time();
                $arr[$a]['b_id']=$v['b_id'];
                $arr[$a]['m_id']=session('admin.id');
                $a++;
            }
        }
        $result=DB::name('wx_template_log')->insertAll($arr);
        if ($result) return['code'=>1,'msg'=>'推送成功'];
    }

    public function send_school_single($ids = ""){
       if (empty($ids)) return['code'=>0];
        $wx=new WechatTemplateService();
        $thismonth = date('m');
        $thisyear = date('Y');
        $startDay = $thisyear . '-' . $thismonth . '-1';
        $endDay = $thisyear . '-' . $thismonth . '-' . date('t', strtotime($startDay));
        $start_time= strtotime($startDay);//当前月的月初时间戳
        $end_time = strtotime($endDay)+86400;//当前月的月末时间戳
        $data=DB::name('school_bind')->where(['id'=>$ids])->find();
        if (empty($data['openid']))return['code'=>0,'msg'=>'openid错误'];
        $views=DB::name('zd_user_school_click')->where("create_time>".$start_time." and create_time<".$end_time."")->where(['school_id'=>$data['school_id']])->group('user_id')->count();
        $follows=DB::name('zd_user_school_follow')->where("create_time>".$start_time." and create_time<".$end_time."  and type=0")->where(['school_id'=>$data['school_id']])->count();
        $content=array('first' => '您好，已为您生成本月运营报告，请查收',
            'keyword1' => '运营月报',
            'keyword2' => date('Y-m-d H:i:s', time()),
            'remark' => "".$data['school']."本月访客 ".$views." 人，新增关注用户 ".$follows." 人 更多信息请登录后台查看");
        $res=$wx->sendTemplate1($data['openid'],2,$content);
        $arr['school_id']=$data['school_id'];
        $arr['school']=$data['school'];
        $arr['openid']=$data['openid'];
        $arr['name']=$data['name'];
        $arr['code']=$res['errcode']?$res['errcode']:1;
        $arr['msg']=$res['errmsg']?$res['errmsg']:'fail';
        $arr['time']=time();
        $arr['b_id']=$data['id'];
        $arr['m_id']=session('admin.id');
        $result=DB::name('wx_template_log')->insert($arr);
        if ($result) return['code'=>1,'msg'=>'推送成功'];
    }
}
